package com.demo.config.security;

import com.demo.common.JsonResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

import static org.springframework.security.config.Customizer.withDefaults;


@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class SecurityConfig  {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {


        http
                .authorizeHttpRequests((authorize) -> authorize
                        .antMatchers("/test/**").permitAll()
                        .anyRequest()
                        .authenticated()
                )
                .httpBasic(withDefaults());


        http.formLogin((e)->{
            e.loginProcessingUrl("/user/login");
            e.successHandler((rt,re,v)->{
                System.out.println("登入");
                re.setContentType("text/json;charset=UTF-8");
                re.getWriter().write(new ObjectMapper().writeValueAsString(JsonResult.okMsg("登入成功!")));
            });
            e.failureHandler((rt,re,v)->{
                v.printStackTrace();
                re.setContentType("text/json;charset=UTF-8");
                re.getWriter().write(new ObjectMapper().writeValueAsString(JsonResult.fail("登入失败!")));
            });

        });


        http.logout((l)->{
            l.logoutUrl("/user/logout");
            l.logoutSuccessHandler((rt,re,v)->{
                re.setContentType("text/json;charset=UTF-8");
                re.getWriter().write(new ObjectMapper().writeValueAsString(JsonResult.okMsg("登出成功!")));
            });
        });

        return http.build();
    }

    //配置密码认证器
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


}